package com.easy.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.SysPermission;
import com.easy.common.bean.SysRole;
import com.easy.common.bean.SysUser;
import com.easy.common.service.IRoleService;
import com.easy.user.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class RoleService extends ServiceImpl<RoleMapper,SysRole> implements IRoleService {
    @Autowired
    RoleMapper roleMapper;
    @Override
    public SysRole insert(SysRole role) {
        roleMapper.insert(role);
        SysRole result=this.getByID(role.getId());
        return result;
    }

    @Override
    public SysRole update(SysRole role) {
        roleMapper.updateById(role);
        SysRole result=this.getByID(role.getId());
        return result;
    }

    @Override
    public int delete(Integer id) {
        int num=roleMapper.deleteById(id);
        return num;
    }

    @Override
    public SysRole getByID(Integer id) {
        SysRole result=roleMapper.selectById(id);
        return result;
    }

    @Override
    public IPage<SysRole> getListByPage(IPage page, SysRole role) {

        Wrapper wrapper=new QueryWrapper(role);
        IPage result=roleMapper.selectPage(page,wrapper);
        return result;
    }

    @Override
    public List<SysRole> getList(SysRole role) {
        Wrapper wrapper=new QueryWrapper(role);
        List<SysRole> result=roleMapper.selectList(wrapper);
        return result;
    }

    @Override
    public int setStatus(Integer id) {
        return 0;
    }

    @Override
    public SysRole assignPermission(SysRole role) {
        return null;
    }

    @Autowired
    private PermissionService permissionService;

    @Override
    public SysRole getPermissionByID(Integer id){
        // 1. 查询角色基本信息
        SysRole role = roleMapper.selectById(id);
        if (role != null) {
            // 2. 查询角色关联的权限ID列表
            List<Integer> permissionIds = baseMapper.getPermissionIdsByRoleId(id);
            // 3. 根据权限ID获取权限对象并填充到角色中
            List<SysPermission> permissions = permissionIds.stream()
                    .map(permissionService::getByID)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            role.setPermissions(permissions);
        }
        return role;
    }
}
